package com.luoxiang.socialandroid.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.luoxiang.lib_common.bean.NumberBean
import com.luoxiang.lib_common.common.Constants
import com.luoxiang.lib_common.utils.NetUtils
import com.luoxiang.socialandroid.R
import com.luoxiang.socialandroid.activity.DetailsActivity
import com.luoxiang.socialandroid.adapter.CharmListAdapter
import com.luoxiang.socialandroid.adapter.CharmListDayAdapter
import com.luoxiang.socialandroid.base.LazyLoadFragment
import com.luoxiang.socialandroid.bean.ListBean
import com.luoxiang.socialandroid.bean.ListData
import com.luoxiang.socialandroid.bean.ListDetail
import com.luoxiang.socialandroid.bean.RewardBean
import com.luoxiang.socialandroid.common.Constants.MmkvConst.ACCID
import com.luoxiang.socialandroid.common.Constants.MmkvConst.USERID
import com.luoxiang.socialandroid.databinding.FragmentCharmSubBinding
import com.luoxiang.socialandroid.utils.AESUtil
import com.luoxiang.socialandroid.utils.MmkvUtil
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

/**
 * Author: fuxinbo

 * Date: 2023/2/9

 * Description:
 */
class CharmSubFragment : LazyLoadFragment() {
    private lateinit var binding: FragmentCharmSubBinding

    private var mAdapter: BaseQuickAdapter<ListDetail, BaseViewHolder>? = null

    private var mCurrentListType: Int = 0

    private val map: HashMap<Int, ListDetail> = hashMapOf()

    override fun setContentView(): Int = R.layout.fragment_charm_sub

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentCharmSubBinding.inflate(layoutInflater)
        super.onCreateView(inflater, container, savedInstanceState)
        return binding.root
    }

    override fun initView() {
        mCurrentListType = arguments?.getInt(PAGE_TYPE, 0) ?: 0
        initAdapter()
        binding.ivState.setOnClickListener {
            if (map[1]?.status == 0 || MmkvUtil.decodeInt(USERID)
                    ?.toLong() != map[1]?.userId
            ) return@setOnClickListener
            claimReward(map[1]?.id?.toString() ?: "", img = binding.ivState)
        }
        binding.ivTwoState.setOnClickListener {
            if (map[2]?.status == 0 || MmkvUtil.decodeInt(USERID)
                    ?.toLong() != map[2]?.userId
            ) return@setOnClickListener
            claimReward(map[2]?.id?.toString() ?: "", img = binding.ivTwoState)
        }
        binding.ivThreeState.setOnClickListener {
            if (map[3]?.status == 0 || MmkvUtil.decodeInt(USERID)
                    ?.toLong() != map[3]?.userId
            ) return@setOnClickListener
            claimReward(map[3]?.id?.toString() ?: "", img = binding.ivThreeState)
        }
    }

    override fun onResume() {
        super.onResume()
        getInviteListData()
    }

    override fun lazyLoad() {
    }

    private fun initAdapter() {
        mAdapter = if (mCurrentListType == 1 || mCurrentListType == 2) {
            CharmListDayAdapter()
        } else {
            CharmListAdapter()
        }
        binding.recyclerList.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            setHasFixedSize(true)
        }
        mAdapter?.addChildClickViewIds(R.id.textReceive)
        mAdapter?.addChildClickViewIds(R.id.imageUser)
        mAdapter?.setOnItemChildClickListener { adapter, view, position ->
            (adapter.data[position] as? ListDetail)?.let {
                when (view.id) {
                    R.id.imageUser -> {
                        toUserDetailPage(it.userId.toInt())
                    }

                    R.id.textReceive -> {
                        if (it.status == 0 || MmkvUtil.decodeInt(USERID)
                                ?.toLong() != it.userId
                        ) return@let
                        claimReward(it.id.toString(), isList = true, position = position)
                    }
                }
            }
        }
    }

    private fun getInviteListData() {
        NetUtils.getInstance().apiService.getInviteListData(
            Constants.MmkvConst.EXTRA,
            MmkvUtil.decodeString(Constants.MmkvConst.TOKEN),
            1,
            when (mCurrentListType) {
                0 -> 3
                1 -> 0
                2 -> 1
                else -> 3
            }
        ).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<NumberBean> {
                override fun onSubscribe(d: Disposable?) {}

                override fun onError(e: Throwable?) {}

                override fun onComplete() {}

                override fun onNext(value: NumberBean?) {
                    val data = value?.data
                    var decryptStr: String? = null
                    try {
                        decryptStr = AESUtil.aesDecryptString(data, Constants.MmkvConst.KEY)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    LogUtils.i("decryptStr10", decryptStr)
                    val listData = Gson().fromJson<ListBean>(
                        decryptStr,
                        object : TypeToken<ListBean>() {}.type
                    )
                    listData?.data?.let {
                        setTopThreeData(it)
                        setListData(it)
                    }
                }
            })
    }

    private fun setTopThreeData(data: ListData) {
        if (data.tops.isEmpty()) {
            return
        }
        data.tops[0].let { list ->
            binding.tvOneUserName.text = list.name
            map[1] = list
            binding.tvReward.text = if (mCurrentListType == 1 || mCurrentListType == 2) {
                binding.ivState.visibility = View.GONE
                ""
            } else {
                binding.ivState.visibility = View.VISIBLE
                "奖励：${list.reward}元"
            }
            binding.imageUserOne.setOnClickListener {
                toUserDetailPage(map[1]?.userId?.toInt())
            }
            Glide.with(contentView).load(domain + list.icon)
                .apply(RequestOptions.bitmapTransform(CircleCrop()))
                .into(binding.imageUserOne)
            setRewardState(binding.ivState, list.status)
        }
        data.tops.remove(data.tops[0])

        if (data.tops.isEmpty()) {
            return
        }
        map[2] = data.tops[0]
        binding.tvTwoUserName.text = data.tops[0].name
        binding.tvTwoReward.text = if (mCurrentListType == 1 || mCurrentListType == 2) {
            binding.ivTwoState.visibility = View.GONE
            "距上名差：${data.tops[0].distance}积分"
        } else {
            binding.ivTwoState.visibility = View.VISIBLE
            "奖励：${data.tops[0].reward}元"
        }
        binding.imageUserTwo.setOnClickListener {
            toUserDetailPage(map[2]?.userId?.toInt())
        }
        setRewardState(binding.ivTwoState, data.tops[0].status)
        Glide.with(contentView).load(domain + data.tops[0].icon)
            .apply(RequestOptions.bitmapTransform(CircleCrop()))
            .into(binding.imageUserTwo)
        data.tops.remove(data.tops[0])

        if (data.tops.isEmpty()) {
            return
        }
        map[3] = data.tops[0]
        binding.tvThreeUserName.text = data.tops[0].name
        binding.tvThreeReward.text = if (mCurrentListType == 1 || mCurrentListType == 2) {
            binding.ivThreeState.visibility = View.GONE
            "距上名差：${data.tops[0].distance}积分"
        } else {
            binding.ivThreeState.visibility = View.VISIBLE
            "奖励：${data.tops[0].reward}元"
        }
        binding.imageUserThree.setOnClickListener {
            toUserDetailPage(map[3]?.userId?.toInt())
        }
        setRewardState(binding.ivThreeState, data.tops[0].status)
        Glide.with(contentView).load(domain + data.tops[0].icon)
            .apply(RequestOptions.bitmapTransform(CircleCrop()))
            .into(binding.imageUserThree)
        data.tops.remove(data.tops[0])
    }

    private fun setListData(data: ListData) {
        if (data.tops.isEmpty()) return
        mAdapter?.setList(data.tops)
    }

    private fun setRewardState(img: TextView?, status: Int? = 1) {
        img?.text = if (status == 0) "已领取" else "未领取"
        img?.setBackgroundResource(if (status == 0) R.drawable.bg_list_item_receive else R.drawable.bg_list_item_no_receive)
        img?.setTextColor(
            if (status == 0) ContextCompat.getColor(
                requireContext(),
                R.color.black
            ) else ContextCompat.getColor(requireContext(), R.color.white)
        )
    }

    private fun claimReward(
        id: String, img: TextView? = null, isList: Boolean = false, position: Int = 0
    ) {
        NetUtils.getInstance().apiService.claimReward(
            Constants.MmkvConst.EXTRA,
            MmkvUtil.decodeString(Constants.MmkvConst.TOKEN),
            id
        ).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<NumberBean> {
                override fun onSubscribe(d: Disposable?) {}

                override fun onError(e: Throwable?) {
                    Toast.makeText(requireContext(), e?.message, Toast.LENGTH_SHORT).show()
                }

                override fun onComplete() {}

                override fun onNext(value: NumberBean?) {
                    val data = value?.data
                    var decryptStr: String? = null
                    try {
                        decryptStr = AESUtil.aesDecryptString(data, Constants.MmkvConst.KEY)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    val bean = Gson().fromJson<RewardBean>(
                        decryptStr,
                        object : TypeToken<RewardBean>() {}.type
                    )
                    if (bean.code == 1) {
                        Toast.makeText(context, bean.msg, Toast.LENGTH_SHORT).show()
                        return
                    }
                    if (isList) {
                        (mAdapter!!.data[position] as? ListDetail)?.let {
                            it.status = 0
                        }
                        mAdapter?.notifyItemChanged(position)
                    } else {
                        setRewardState(img, 0)
                    }
                }
            })
    }

    private fun toUserDetailPage(userId: Int?) {
        userId ?: return
        startActivity(Intent(requireContext(), DetailsActivity::class.java).apply {
            putExtra("userid", userId)
        })
    }
}